package cn.kimming.wms.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.kimming.wms.dao.IOrderBillDAO;
import cn.kimming.wms.domain.OrderBill;
import cn.kimming.wms.domain.OrderBillItem;
import cn.kimming.wms.query.QueryObject;
import cn.kimming.wms.service.IOrderBillService;
import cn.kimming.wms.util.OrderCodeFactory;
import cn.kimming.wms.util.UserContext;

@Service("orderBillService")
public class OrderBillServiceImpl implements IOrderBillService {

	@Autowired
	private IOrderBillDAO orderBillDAO;
	
	@Override
	public void save(OrderBill bill) {
		//0.生成采购订单编号
		bill.setSn(OrderCodeFactory.getOrderCode(UserContext.getUser().getId()));
		//1.设置制单人和制单时间
		bill.setInputUser(UserContext.getUser());
		bill.setInputTime(new Date());
		//2.重新设置订单的未审核状态, 初始化订单的总数量和总金额
		bill.setStatus(OrderBill.NORMAL);
		//3.处理订单明细
		handleRelation(bill);
		//4.保存订单
		orderBillDAO.save(bill);
	}
	
	//抽取方法:专门用来处理订单和明细之间的关系
	private void handleRelation(OrderBill bill) {
		bill.setTotalNumber(BigDecimal.ZERO);
		bill.setTotalAmount(BigDecimal.ZERO);
		for (OrderBillItem item : bill.getItems()) {
			//设置订单和明细之间的关系
			item.setBill(bill);
			//计算明细小计
			item.setAmount(item.getCostPrice().multiply(item.getNumber()).setScale(2, RoundingMode.HALF_UP));
			//计算订单的总数量和总金额
			bill.setTotalNumber(bill.getTotalNumber().add(item.getNumber()));
			bill.setTotalAmount(bill.getTotalAmount().add(item.getAmount()));
		}
	}
	
	@Override
	public void update(OrderBill bill) {
		//首先判断订单的状态:只有未审核的订单才可以做更新操作
		if (bill.getStatus() == OrderBill.NORMAL) {
			handleRelation(bill);
			orderBillDAO.update(bill);
		}
	}

	@Override
	public void delete(Long id) {
		orderBillDAO.delete(orderBillDAO.get(id));
		
	}

	@Override
	public OrderBill get(Long id) {
		return orderBillDAO.get(id);
	}

	@Override
	public List<OrderBill> list() {
		return orderBillDAO.list();
	}

	@Override
	public List<OrderBill> query(QueryObject qo) {
		return orderBillDAO.query(qo);
	}

	@Override
	public void audit(Long billId) {
		OrderBill bill = orderBillDAO.get(billId);
		if (bill == null) {
			throw new NullPointerException("审核失败, 无效订单!");
		}
		//判断订单状态
		if (bill.getStatus() == OrderBill.NORMAL) {
			//修改订单状态
			bill.setStatus(OrderBill.AUDIT);
			//设置审核人和审核时间
			bill.setAuditor(UserContext.getUser());
			bill.setAuditTime(new Date());
			//更新订单
			orderBillDAO.update(bill);
		}
	}
}
